package com.iv.durian.cloud.api.service;

import com.iv.durian.cloud.User;
import com.iv.durian.cloud.facade.RandomCodeFacade;
import com.iv.durian.cloud.facade.UserFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    private PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    //private TextEncryptor textEncryptor = Encryptors.text("durian-cloud-api","durian");

    @Autowired
    private UserFacade userFacade;

    @Autowired
    private RandomCodeFacade randomCodeFacade;

    public User getUserById(Integer userId){
        return userFacade.get(userId);
    }

    public User getUserByMobileOrEmail(String mobileOrEmail){
        return userFacade.get(mobileOrEmail);
    }

    public User getUserByAccessToken(String accessToken){
        return userFacade.getByTicket(accessToken);
    }

    public boolean verifyPassword(User user,String password){
        String passwordTicket = passwordEncoder.encode(password);
        return StringUtils.equals(passwordTicket,user.getPassword());
    }

    public String generateAccessToken(User user){
        String encryptedText = "{" +"id:" + user.getId()+ ",mobile:" + user.getMobile() + ",email:" + user.getEmail() + ",status:" + user.getStatus() + "}";
       // return textEncryptor.decrypt(encryptedText);
        return encryptedText;
    }

    public String generateCode( String userKey){
        //TODO 根据userKey格式生成Code  手机号--发送短信  邮箱--发邮件
        return randomCodeFacade.generateCode(userKey);
    }

    public boolean verifyCode(String userKey,String code){
        return randomCodeFacade.verifyCode(userKey , code);
    }

    public void addUser(User user){
        String passwordTicket = passwordEncoder.encode(user.getPassword());
        user.setPassword(passwordTicket);
        userFacade.add(user);
    }

    public void updatePassword(Integer userId,String password){
        String passwordTicket = passwordEncoder.encode(password);
        userFacade.updatePassword(userId,passwordTicket);
    }

    public int updateTicket( int id, String ticket,long expire){
        return userFacade.updateTicket(id,ticket,expire);
    }

    public int cleanTicket( int id){
        return userFacade.cleanTicket(id);
    }



}
